package com.yoomiito.app.widget

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.utils.ColorUtils
import com.yoomiito.app.utils.DensityUtil
import com.yoomiito.app.utils.L
import com.yoomiito.app.utils.ResUtil


class PopupTip(val context: Context, view: View, var content: String) : PopupWindow(context) {
    private val view1 = View(context).let {
//        it.background = ResUtil.getDrawable(R.drawable.triangle_up)
        it
    }
    private val tv = TextView(context).let {
        it.text = content
        it.setTextColor(ResUtil.getColor(R.color.color_white))
        it.textSize = 12f
        val l = DensityUtil.dp2px(10f)
        val t = DensityUtil.dp2px(6f)
        it.setPadding(l, t, l, t)
        it.background = ColorUtils.gradientAndRadius("#FFFF246C", "#FFFF035B", DensityUtil.dp2px(4f).toFloat())
        it
    }

    private val parentView = LinearLayout(context).let {
        it.orientation = LinearLayout.VERTICAL
        it.addView(view1, LinearLayout.LayoutParams(DensityUtil.dp2px(10f), DensityUtil.dp2px(5f)))
        it.addView(tv, LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT))
        it.setBackgroundColor(Color.parseColor("#000fff"))
        it
    }

    init {
        parentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
        contentView = parentView
        isOutsideTouchable = false
        setBackgroundDrawable(ColorDrawable(Color.parseColor("#00000000")))

        val location = IntArray(2)
        view.getLocationOnScreen(location)
        val viewX = location[0]
        val viewY = location[1]
        val viewW = view.width
        val viewH = view.height
        val pw = parentView.measuredWidth
//        val ph = parentView.measuredHeight
        val pw2 = pw / 2
        val mrx = App.mWidthPx - viewW - viewX
        var y = viewY + viewH
        var x = when {
            pw2 >= viewX -> {
                //靠左
                viewX
            }
            pw2 >= mrx -> {
                //靠右
                viewX+viewW-pw
            }
            else -> {
                //居中
                viewX+viewW/2-pw2
            }
        }

        showAtLocation(view, Gravity.NO_GRAVITY, x, y)
    }

}